package com.nelson.musicplayer.business.home.repository

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.nelson.musicplayer.source.api.HomeService
import com.nelson.musicplayer.manager.RequestManager
import com.nelson.musicplayer.source.Resource
import com.nelson.musicplayer.source.bean.HomeData
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

object HomeRepository {
    private var mService: HomeService = RequestManager.createHomeService()

    fun fetchHomeData(): LiveData<Resource<HomeData?>> {
        val responseData = MutableLiveData<Resource<HomeData?>>();
        responseData.postValue(Resource.loading(null))
        val fetchFirstVideoCall = mService.fetchHomeData()
        fetchFirstVideoCall.enqueue(object : Callback<HomeData> {
            override fun onFailure(call: Call<HomeData>, t: Throwable) {
                responseData.postValue(Resource.error(null, "网络请求失败", t))
            }

            override fun onResponse(call: Call<HomeData>, response: Response<HomeData>) {
                if (response.isSuccessful) {
                    responseData.postValue(Resource.success(response.body()))
                } else {
                    responseData.postValue(Resource.error(null, "网络请求失败", null))
                }
            }
        })
        return responseData
    }
}